package com.tao.friend.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tao.common.creo.domain.TableDataInfo;
import com.tao.friend.domain.exam.dto.ExamQueryDTO;
import com.tao.friend.domain.exam.vo.ExamQueryVO;
import com.tao.friend.domain.exam.vo.ExamVO;
import com.tao.friend.manager.ExamCacheManager;
import com.tao.friend.mapper.ExamMapper;
import com.tao.friend.service.IExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class ExamServiceImpl implements IExamService {


    @Autowired
    ExamMapper examMapper;

    @Autowired
    private ExamCacheManager examCacheManager;
    @Override
    public List<ExamQueryVO> list(ExamQueryDTO examQueryDTO) {
        PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
        return examMapper.selectExamList(examQueryDTO);
    }


    /**
     * redis 存储键值对
     * key: e:t:l         values  (未完赛)
     * key: e:h:l         values  (已完赛)
     * key: e:d:examId    values  (竞赛基本信息)
     * @param examQueryDTO
     */
    @Override
    public TableDataInfo redisList(ExamQueryDTO examQueryDTO) {
        // 从redis中获取长度  根据类型获取
        Long total = examCacheManager.getListSize(examQueryDTO.getType());
        // 判断长度
        List<ExamQueryVO> examQueryVOS;
        if (total == null || total <= 0) {
            // 长度为空, 从数据库中查询并且把查询到的数据存储到redis中
            examQueryVOS = list(examQueryDTO);
            // 存入将查询到的数据存储到 redis 中
            examCacheManager.refreshCache(examQueryDTO.getType(), null);
            // 获取总数
            total = new PageInfo<>(examQueryVOS).getTotal(); // 获取总数
        }else {
            // 长度不为空, 从redis拿
            examQueryVOS = examCacheManager.getExamVOList(examQueryDTO, null);
        }
        // 返回数据
        if(CollectionUtils.isEmpty(examQueryVOS)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(examQueryVOS, total);
    }
}
